How is a switch statement better than a series of if statements? [closed]
Posted
by
user1276078
on Programmers
See other posts from Programmers
or by user1276078
Published on 2012-06-27T17:10:08Z
Indexed on
2012/06/27
21:25 UTC
Read the original article
Hit count: 225
java
|switch-statement
Possible Duplicate:
Should I use switch statements or long if…else chains?
I'm working on a small program that will conduct an Insertion Sort. A number will be inputted through the keyboard and stored in a variable I called "num." I've decided to use a switch statement in order to obtain the number inputted.
switch( e.getKeyCode() ) {
case KeyEvent.VK_0: num = 0; break;
case KeyEvent.VK_1: num = 1; break;
case KeyEvent.VK_2: num = 2; break;
case KeyEvent.VK_3: num = 3; break;
case KeyEvent.VK_4: num = 4; break;
case KeyEvent.VK_5: num = 5; break;
case KeyEvent.VK_6: num = 6; break;
case KeyEvent.VK_7: num = 7; break;
case KeyEvent.VK_8: num = 8; break;
case KeyEvent.VK_9: num = 9; break;
}
I realized one other course of action could have been to use a set of if statements.
if( e.getKeyCode() == KeyEvent.VK_0 )
num = 0;
else if( e.getKeyCode() == KeyEvent.VK_1 )
num = 1;
etc. for every number up until 9.
I then wondered what the essential difference is between a switch statement and a series of if statements. I know it saves space and time to write, but it's not that much. So, my question is, aside from the space, does a switch statement differ from a series of if statments in any way? Is it faster, less error-prone, etc.?
This question really doesn't affect my code that much. I was just wondering. Also, this question pertains to the JAVA language, not any other programming language.
© Programmers or respective owner